package cn.net.zj.scan.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanDevice;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.net.zj.scan.R;
import cn.net.zj.scan.adapter.InHouseListAdapter;
import cn.net.zj.scan.api.HttpMethods;
import cn.net.zj.scan.base.Result;
import cn.net.zj.scan.bean.InHouseBean;
import cn.net.zj.scan.bean.LabelBean;
import cn.net.zj.scan.bean.StateBean;
import cn.net.zj.scan.utils.SharedPreferencesUtils;
import cn.net.zj.scan.utils.ToastUtils;
import cn.net.zj.scan.utils.ZjConfig;
import cn.net.zj.scan.zxing.utils.BeepManager;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by Huan on 2018/5/11.
 * 扫码入库
 */

public class InHouseActivity extends BaseActivity {

    //<editor-fold desc=”成员变量”>
    @BindView(R.id.tv_result)
    TextView tv_result;

    @BindView(R.id.tv_title)
    TextView tv_title;

    @BindView(R.id.etBill)
    EditText etBill;

    @BindView(R.id.recycleView)
    RecyclerView recycleView;


    private InHouseListAdapter inHouseListAdapter;
    private BeepManager beepManager;
    private List<LabelBean> labelList = new ArrayList<>();

    private Boolean isBusy = false;
    private ScanDevice sm;
    private final static String SCAN_ACTION = "com.action.SCAN_RESULT";
    private String barcodeStr;

    private boolean canScan = false;

    //</editor-fold>

    //<editor-fold desc=”重写”>

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_in_house;
    }


    @Override
    public void init() {
        super.init();
        tv_title.setText("扫码入库");

        String fBillNo = getIntent().getStringExtra("FBillNo");
        if (!StringUtils.isEmpty(fBillNo)) {
            etBill.setText(fBillNo);
        }

        try {
            sm = new ScanDevice();
            sm.setOutScanMode(ScanDevice.SCANNER_MODE_BROADCAST);
            sm.openScan();
        } catch (Exception e) {
            ToastUtils.showToast("不支持此手机,请用指定的终端机扫码");
        }
        inHouseListAdapter = new InHouseListAdapter(this, labelList);
        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setStackFromEnd(true);//列表再底部开始展示,反转后由上面开始展示
        layout.setReverseLayout(true);//列表翻转
        recycleView.setLayoutManager(layout);
        recycleView.setAdapter(inHouseListAdapter);
    }


    //</editor-fold>

    //<editor-fold desc=”生命周期”>


    @Override
    protected void onPause() {
        super.onPause();
        if (sm != null) {
            sm.stopScan();
        }
        unregisterReceiver(mScanReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);
        registerReceiver(mScanReceiver, filter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    // 回调方法，从第二个页面回来的时候会执行这个方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        // 根据上面发送过去的请求吗来区别
        switch (requestCode) {
            case ZjConfig.request_out_Code:
                break;
            case ZjConfig.request_in_Code:
                if (data != null) {

                    if (isBusy) {
                        ToastUtils.showToast("正在入库中，请稍后操作");
                    } else {
                        String change01 = data.getStringExtra("result_string");
                        processResult(change01);
                    }

                }
                break;
            default:
                break;
        }
    }
    //</editor-fold>

    //<editor-fold desc=”私有方法”>


    private void processResult(String resultData) {
        if (resultData.startsWith("R_")) {
            etBill.setText(resultData);
            canScan = false;
            return;
        }

        if (etBill.getText().length() == 0) {
            com.blankj.utilcode.util.ToastUtils.showShort("请输入任务单号，并验证。");
            return;
        }


        if (!canScan) {
            com.blankj.utilcode.util.ToastUtils.showShort("请验证任务单号。");
            return;
        }



        String[] b = resultData.split("\\s+");  //以每个A作为分割点,得到的是
        if (b.length < 3) {
            ToastUtils.showToast("标签不合法!!!");
            return;
        }
        String[] c = b[3].split("-");
        tv_result.setText("产品名称:" + b[0] + "\r\n" + " 产品配方:" + b[1] + "\r\n" + "  仓位:" + b[2] + "\r\n" + "  批号" + c[0] + "\r\n" + "  本批次顺序号:" + c[1]
                + "\r\n" + "返回结果" + resultData);

        String userName = (String) SharedPreferencesUtils.getParam(this, ZjConfig.userName, "");

        InHouseBean bean = new InHouseBean();
        bean.setR_icmobill(etBill.getText().toString());
        bean.setR_name(b[0]);
        bean.setR_spectype(b[1]);
        bean.setR_stockno(b[2]);
        bean.setR_batchno(c[0]);
        bean.setR_number(b[3]);
        bean.setR_time(TimeUtils.getNowString());
        bean.setUserName(userName);

        Gson gson = new Gson();
        String dataString = gson.toJson(bean);
        submitData(dataString, resultData);
    }


    @OnClick({R.id.btValidation, R.id.bt_start_scan})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btValidation:
                if (etBill.getText().length() > 0) {
                    HashMap<String, String> params = new HashMap<>();
                    params.put("R_icmobill", etBill.getText().toString());
                    HttpMethods.getInstance().getFyApi().validateBill(params)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new SingleObserver<Result<Map>>() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onSuccess(Result<Map> value) {
                                    if (!value.getFlag().equals("True")) {
                                        com.blankj.utilcode.util.ToastUtils.showLong(value.getMessage());
                                        return;
                                    }
                                    canScan = true;

                                    labelList.clear();
                                    inHouseListAdapter.clear();
                                    recycleView.requestFocus();
                                    hideSoftkeyboard();
                                    com.blankj.utilcode.util.ToastUtils.showLong("请开始扫商品");
                                }

                                @Override
                                public void onError(Throwable e) {
                                    com.blankj.utilcode.util.ToastUtils.showLong(e.toString());
                                }
                            });
                }


                break;
            case R.id.bt_start_scan:
                if (isBusy) {
                    ToastUtils.showToast("正在入库中，请稍后操作");
                } else {
                    sm.startScan();
                }
                break;
        }
    }

    //</editor-fold>

    //<editor-fold desc=”request”>


    private void submitData(String dataString, final String label) {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), dataString);
        Observable<StateBean> observable = HttpMethods.getInstance().getFyApi().inHouse(body);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<StateBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        isBusy = true;
                    }

                    @Override
                    public void onNext(final StateBean resBean) {
                        dismissProgress();
                        LabelBean bean = new LabelBean();
                        bean.setLabelId("标签码：" + label);
                        if (resBean.isFlag()) {
                            beepManager = new BeepManager(InHouseActivity.this, R.raw.sure);
                            beepManager.playBeepSoundAndVibrate();
                            bean.setState("入库成功");
                            labelList.add(bean);
                            inHouseListAdapter.notifyDataSetChanged();
                        } else {
                            beepManager = new BeepManager(InHouseActivity.this, R.raw.error);
                            beepManager.playBeepSoundAndVibrate();
//                            bean.setState("入库失败:" + resBean.getMessage());
                            com.blankj.utilcode.util.ToastUtils.showShort(resBean.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showToast("连接异常：" + e);
                        dismissProgress();
                        isBusy = false;
                    }

                    @Override
                    public void onComplete() {
                        isBusy = false;
                        dismissProgress();
                    }
                });

    }

    //</editor-fold>


    //<editor-fold desc=”内部类”>


    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            byte[] barcodeArray = intent.getByteArrayExtra("scanContext");
            barcodeStr = new String(barcodeArray, 0, barcodeArray.length);
            processResult(barcodeStr);
            sm.stopScan();
        }

    };

    //</editor-fold>


}
